package com.easylinkin.linkappapi.ruleengine.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogOperateType;
import com.easylinkin.linkappapi.ruleengine.entity.RuleEngine;
import com.easylinkin.linkappapi.ruleengine.service.RuleEngineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * <p>
 * 智能规则引擎 前端控制器
 * </p>
 *
 * @author TongJie
 * @since 2020-08-24
 */
@Slf4j
@Api(value="智能规则引擎",tags={"智能规则引擎"})
@RestController
@RequestMapping("/ruleEngine")
public class RuleEngineController {

    @Resource
    private RuleEngineService service;

    @ApiOperation("触发规则引擎联动")
    @PostMapping("trigger")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "触发规则引擎联动")
    public RestMessage trigger(@RequestBody RuleEngine ruleEngine) {
        service.trigger(ruleEngine);
        return RestBuilders.successBuilder().build();
    }


    /**
     * 配置
     */
    @ApiOperation("配置规则引擎")
    @PostMapping("setDetailConfig")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "")
    public RestMessage setDetailConfig(@RequestBody RuleEngine ruleEngine) {
        Assert.hasLength(ruleEngine.getId(), "规则引擎id参数为空");
        RuleEngine ruleEngineOld = service.getById(ruleEngine.getId());
        LogHelper.setContent(LogOperateType.RULE_ENGINE_UPDATE,ruleEngineOld.getName());
        service.setDetailConfig(ruleEngine);
        return RestBuilders.successBuilder().build();
    }

    @ApiOperation("新增规则引擎")
    @PostMapping("add")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "新增规则引擎")
    public RestMessage add(@RequestBody RuleEngine ruleEngine) {
        service.add(ruleEngine);
        return RestBuilders.successBuilder().build();
    }

    @ApiOperation("修改规则引擎")
    @PostMapping("update")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "修改规则引擎")
    public RestMessage update(@RequestBody RuleEngine ruleEngine) {
        service.updateRuleEngine(ruleEngine);
        return RestBuilders.successBuilder().build();
    }

    @ApiOperation("修改规则引擎状态")
    @PostMapping("updateStatus")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "修改规则引擎状态")
    public RestMessage updateStatus(@RequestBody RuleEngine ruleEngine) {
        service.updateStatus(ruleEngine);
        return RestBuilders.successBuilder().build();
    }

    @ApiOperation("根据查询条件获取规则引擎数据")
    @PostMapping("get")
    public RestMessage getRuleEngines(@RequestBody RuleEngine ruleEngine) {
        Assert.notNull(ruleEngine, "ruleEngine 不能为空");
        return RestBuilders.successBuilder().data(service.getRuleEngines(ruleEngine)).build();
    }

    @ApiOperation("获取规则引擎分页列表")
    @PostMapping("getPage")
    public RestMessage getRuleEnginesPage(@RequestBody RequestModel<RuleEngine> requestModel) {
        Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<RuleEngine> record = service.getRuleEngines(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder().data(record).build();
    }

    @ApiOperation("根据规则引擎ID获取单个引擎数据")
    @PostMapping("getById")
    public RestMessage getById(@RequestParam("id") String id) {

        return RestBuilders.successBuilder().data(service.getRuleEngine(id)).build();
    }

    @ApiOperation("批量删除规则引擎")
    @PostMapping("deleteBatch")
    @CommonOperateLogAnnotate(module = LogModule.RULE_ENGINE, desc = "")
    public RestMessage deleteBatch(@RequestBody List<RuleEngine> ruleEngineList) {
        Assert.notEmpty(ruleEngineList, "参数为空");
        List<String> ids = ruleEngineList.stream().map(RuleEngine::getId).collect(Collectors
            .toList());
        // 记录日志详情
        List<String> names = new ArrayList<>();
        ids.forEach(p->{
            RuleEngine ruleEngine = service.getRuleEngine(p);
            names.add(ruleEngine.getName());
        });
        if(CollectionUtil.isNotEmpty(names)){
            LogHelper
                .setContent(LogOperateType.RULE_ENGINE_DELETE, StringUtil
                    .join(names,","));
        }
        service.deleteBatch(ruleEngineList);
        return RestBuilders.successBuilder().build();
    }

    @ApiOperation("获取绑定指定设备的规则引擎")
    @PostMapping("getDeviceCodeIsBind")
    public RestMessage getDeviceCodeIsBind(@RequestParam("deviceCode") String deviceCode) {
        try {
            List<RuleEngine> deviceCodeIsBind = service.getDeviceCodeIsBind(deviceCode);
            return RestBuilders.successBuilder().data(deviceCodeIsBind).build();
        }
        catch (IllegalArgumentException e){
            return RestBuilders.failureBuilder().message(e.getMessage()).build();
        }
        catch (Exception e) {
            log.error("分子产品天然气监测,查询设备:{} 绑定错误:{}",deviceCode,e);
            return RestBuilders.failureBuilder().message("查询设备绑定错误").build();
        }
    }

    @ApiOperation("设备编码绑定规则引擎")
    @PostMapping("ruleEngineBindDeviceCode")
    public RestMessage ruleEngineBindDeviceCode(@RequestParam("deviceCode") String deviceCode,@RequestParam("phone") String phone,
                                                @RequestParam(value = "deviceTypeName",required = false) String deviceTypeName) {
        try {
            service.ruleEngineBindDeviceCode(deviceCode,phone,deviceTypeName);
            return RestBuilders.successBuilder().build();
        }catch (IllegalArgumentException e){
            return RestBuilders.failureBuilder().message(e.getMessage()).build();
        } catch (Exception e) {
            log.error("分子产品天然气监测,绑定设备:{} 手机号:{}， 绑定错误:{}",deviceCode,phone,e);
            return RestBuilders.failureBuilder().message("绑定设备错误").build();
        }
    }

    @ApiOperation("解绑设备编码规则引擎绑定关系")
    @PostMapping("ruleEngineRelieveBindDeviceCode")
    public RestMessage ruleEngineRelieveBindDeviceCode(@RequestBody RuleEngine ruleEngine) {
        service.updateStatusBatch(ruleEngine);
        return RestBuilders.successBuilder().build();
    }

}
